package com.tpyule.tpclass.web.Controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tpyule.tpclass.entity.bean.FailResultBean;
import com.tpyule.tpclass.entity.bean.ResultBean;
import com.tpyule.tpclass.entity.bean.SuccessResultBean;
import com.tpyule.tpclass.entity.pojo.Chapter;
import com.tpyule.tpclass.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zzz
 * @version 1.0
 * @date 2020/3/29 13:48
 */
@RestController
@RequestMapping("/chapter")
public class ChapterController extends BaseController{
    @Autowired
    ChapterService chapterService;
    @RequestMapping("/addChapter")
    @ResponseBody
    public void addChapter(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultBean resultBean = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String chapterData = request.getParameter("chapterData");
            Chapter chapter = objectMapper.readValue(chapterData,Chapter.class);
            Chapter result = chapterService.addChapter(chapter);
            if(request==null){
                resultBean = new FailResultBean("添加失败");
            }else {
                resultBean = new SuccessResultBean<Chapter>(result,"添加成功");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } finally {
            this.setAjaxResponseResult(response,resultBean);
        }
    }
    @RequestMapping("/updateChapter")
    @ResponseBody
    public void updateChapter(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultBean resultBean = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String chapterData = request.getParameter("chapterData");
            Chapter chapter = objectMapper.readValue(chapterData,Chapter.class);
            String result = chapterService.updateChapter(chapter);
            if("error".equals(result)){
                resultBean = new FailResultBean("更新失败");
            }else {
                resultBean = new SuccessResultBean<Chapter>(chapter,"更新成功");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } finally {
            this.setAjaxResponseResult(response,resultBean);
        }
    }
}
